<template>
    <el-dialog title="选择优惠券" :visible.sync="dialogVisible" :close-on-click-modal="false">
        <div class="content" @click.stop="()=>{}">
            <el-form label-position="left" label-width="100px" style="width: 100%; padding-left: 20px;">
                <el-form-item label="所选优惠券：" v-if="config.count !== 1">
                    <div class="el-tag-box">
                        <el-tag v-for="(item, index) of result" :key="item.couponActivityId" :closable="true" @close="delItem(index)">{{item.name}}</el-tag>
                    </div>
                </el-form-item>
            </el-form>
            <el-form ref="searchForm" class="search-block" :model="listQuery" label-position="left" label-width="100px" style="width: 100%">
                <input type="text" style="display: none"/><!--form input placeholder-->
                <el-row>
                    <el-col>
                        <el-form-item label="优惠券名称：" prop="name">
                            <el-input @keyup.enter.native="search" v-model="listQuery.name" placeholder="按优惠券名称搜索" maxlength="50" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="" class="btn-item">
                    <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border @row-click="clickRow">
                <el-table-column align="center" width="50">
                    <template slot-scope="scope">
                        <label class="input-radio" v-if="config.count === 1">
                            <input type="radio" :value="{couponActivityId: scope.row.couponActivityId}" v-model="itemsRadio" @change="(e) => setValue(e.target.checked, scope.row)"/>
                            <span></span>
                        </label>
                        <label class="input-checkbox" v-else>
                            <input type="checkbox" :value="{couponActivityId: scope.row.couponActivityId}" v-model="itemsCheck" @change="(e) => setValue(e.target.checked, scope.row)"/>
                            <span></span>
                        </label>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="优惠券名称" prop="name" min-width="100"></el-table-column>
                <el-table-column align="left" label="限定范围" prop="useType" min-width="200" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <template v-if="scope.row.useType==='BY_NONE'">
                            不限制
                        </template>
                        <template v-else>
                            <div class="use-range-block" v-if="scope.row.relationList.filter(item => item.useType === 'BY_USER_TYPE').length">
                                <span>用户角色：</span><div>{{scope.row.relationList.filter(item => item.useType === 'BY_USER_TYPE').map(item => item.relationName).join('、')}}</div>
                            </div>
                            <div class="use-range-block" v-if="scope.row.relationList.filter(item => item.useType === 'BY_MODEL_TYPE').length">
                                <span>商品模式：</span><div>{{scope.row.relationList.filter(item => item.useType === 'BY_MODEL_TYPE').map(item => item.relationName).join('、')}}</div>
                            </div>
                            <div class="use-range-block" v-if="scope.row.relationList.filter(item => item.useType === 'BY_GOODS_TYPE').length">
                                <span>商品分类：</span><div>{{scope.row.relationList.filter(item => item.useType === 'BY_GOODS_TYPE').map(item => item.relationName).join('、')}}</div>
                            </div>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="优惠额度" prop="price" width="90">
                    <template slot-scope="scope">
                        {{scope.row.price}}元
                    </template>
                </el-table-column>
                <el-table-column align="center" label="使用门槛" prop="standardPrice" width="130">
                    <template slot-scope="scope">
                        <span v-if="scope.row.useStandard==='LIMITED'">满{{scope.row.standardPrice}}元</span>
                        <span v-else>无门槛</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="限领数" prop="repeatReceive" width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.repeatReceive===0">不限</span>
                        <span v-else>只能领一次</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="活动状态" prop="activityState" width="80">
                    <template slot-scope="scope">
                        {{activityStateData[scope.row.activeState]}}
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page.sync="listQuery.pageIndex"
                    :page-size="listQuery.pageSize"
                    background
                    layout="total, prev, pager, next, jumper"
                    style="text-align: center"
                    :total="listTotal">
            </el-pagination>
        </div>
        <div slot="footer" class="dialog-footer" @click.stop="()=>{}">
            <el-button type="primary" :loading="btnLoading" @click="choose">确定</el-button>
            <el-button @click="close">取消</el-button>
        </div>
    </el-dialog>
</template>
<script>
  export default {
    name: 'choose-coupon',
    props: {
      config: { type: Object, default(){ return {} } },
      selected: { type: Array, default(){ return [] } }
    },
    data(){
      return {
        activityStateData: {
          'ACTIVITY_STATE_NOT_STARTED': '未开始',
          'ACTIVITY_STATE_ONGOING': '进行中',
          'ACTIVITY_STATE_STOPPED': '已停止',
          'ACTIVITY_STATE_INVALID': '已失效'
        },

        dialogVisible: true,
        btnLoading: false,
        result: this.selected,
        itemsCheck: this.selected.length ? this.selected.map(item => { return { couponActivityId: item.couponActivityId }}): [],
        itemsRadio: this.selected.length ? {couponActivityId: this.selected[0].couponActivityId} : {},

        listQuery: {
          name: '',
          activityState: '',
          pageIndex: 1,
          pageSize: 10
        },
        list: [],
        listTotal: 0,
        listLoading: false
      }
    },
    created(){
      this.getList()
    },
    methods: {
      // 获取列表
      getList() {
        this.listLoading = true;
        let urlCoupon = this.config.validFlag ? '/coupon/system/activity/query/validlist/system/page/search' : '/coupon/system/activity/query'
        if(this.config.receiveType){
          this.listQuery.receiveType = this.config.receiveType
        }
        if(this.config.useTypes){
          this.listQuery.useTypes = this.config.useTypes
        }
        this.request({
          url:urlCoupon,
          method: 'post',
          data: this.listQuery
        }).then(({data, totalCount}) => {
          this.list = data
          this.listTotal = totalCount;
          this.listLoading = false;

        }).catch(err => {
          console.log(err);
          this.list = [];
          this.listTotal = 0;
          this.listLoading = false;
        });
      },
      // 搜索
      search() {
        this.listQuery.pageIndex = 1;
        this.getList();
      },
      // 切换分页
      handleCurrentChange(page) {
        this.listQuery.pageIndex = page;
        this.getList();
      },
      // 选择change
      setValue(checked, row){
        if(checked){
          if(this.config.count ===1 ){
            this.result = [row]
          } else {
            this.result.push({ ...row });
          }
        } else {
          let index = this.itemsCheck.findIndex(item => row.couponActivityId === item.couponActivityId);
          this.result.splice(index, 1);
        }
      },
      // 单击行
      clickRow(row) {
        if (this.config.count === 1) {
          this.itemsRadio = { couponActivityId: row.couponActivityId };
          this.result = [row];
        } else {
          let index = this.itemsCheck.findIndex(item => row.couponActivityId === item.couponActivityId);
          if (index < 0){
            this.itemsCheck.push({ couponActivityId: row.couponActivityId });
            this.result.push({ ...row });
          } else {
            this.itemsCheck.splice(index, 1);
            this.result.splice(index, 1);
          }
        }
      },
      // 通过tag删除
      delItem(index) {
        this.itemsCheck.splice(index, 1);
        this.result.splice(index, 1);
      },
      // 关闭弹窗
      close(){
        this.dialogVisible = false;
        document.body.removeChild(this.$el);
      },
      // 选完，点击确定
      choose(){
        if(this.result.length < 1){
          return this.$message.error('请选择优惠券');
        }
        if(this.config.count > 0 && this.itemsCheck.length > this.config.count){
          return this.$message.error(`最多选择${this.config.count}个优惠券`);
        }
        this.$emit('choose', this.result);
        this.close();
      },

    }
  }
</script>
<style lang="scss" scoped>
  .hide-row{
   display: none;
 }
</style>

